#!/usr/bin/env bash
set -e
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
SFTP_TOOL="$SCRIPT_DIR/../tools/sftp"

REMOTE_PATH=/hygon-devkit/4.0/2025-01-01/csv/confidential-containers/RPMs
if  [ ! -f $SFTP_TOOL ]; then
    wget https://gitee.com/anolis/hygon-devkit/raw/master/tools/sftp
    chmod +x sftp
    FILE_NAMES=$(./sftp list $REMOTE_PATH | grep -oP "kernel-.*?\.rpm")
else
    FILE_NAMES=$($SFTP_TOOL list $REMOTE_PATH | grep -oP "kernel-.*?\.rpm")
fi

LOCAL_DIR=$SCRIPT_DIR/confidential-containers/RPMs
mkdir -p "$LOCAL_DIR"
# loop to install all the rpm packages
for FILE_NAME in $FILE_NAMES; do
    # If the directory don't have the rpm file, download it
    if [ -z "$(ls -A "$LOCAL_DIR"/$FILE_NAME 2>/dev/null)" ] ; then
        if [ ! -f "$SFTP_TOOL" ]; then
            ./sftp download $REMOTE_PATH/$FILE_NAME $LOCAL_DIR/$FILE_NAME
        else
            $SFTP_TOOL download $REMOTE_PATH/$FILE_NAME $LOCAL_DIR/$FILE_NAME
        fi
    fi
done

sudo rpm -ivh --force --nodeps confidential-containers/RPMs/kernel-*.rpm

yum update grub2-efi

grubby --update-kernel=ALL --args="mem_encrypt=on kvm_amd.sev=1"

echo "kernel 5.10 is installed, please reboot the system!"
